<?php

namespace lite\library\storage\engine;

use Qcloud\Cos\Client;

/**
 * 腾讯云存储引擎
 * Class Qcloud
 * @package app\common\library\storage\engine
 */
class Qcloud extends Server
{
    private $config;

    /**
     * 构造方法
     * Qcloud constructor.
     * @param $config
     */
    public function __construct($config)
    {
        parent::__construct();
        $this->config = $config;
    }

    /**
     * @notes 执行上传
     * @param $save_dir
     * @return bool|mixed
     */
    public function upload($save_dir)
    {
        // 要上传图片的本地路径
        $realPath = $this->getRealPath();
        $cosClient = new Client(array(
            'region' => $this->config['region'],
            'credentials' => array(
                'secretId' => $this->config['access_key'],
                'secretKey' => $this->config['secret_key'],
            )
        ));
        
        ### 上传文件流
        try {
            $key = $save_dir . '/' . $this->fileName;
            $result = $cosClient->putObject(array(
                'Bucket' => $this->config['bucket'],
                'Key' => $key,
                'Body' => fopen($realPath, 'rb')));
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            return false;
        }
        return true;
    }

    /**
     * @notes 抓取远程资源
     * @param $url
     * @param null $key
     * @return bool|mixed
     */
    public function fetch($url, $key=null)
    {
        $cosClient = new Client(array(
            'region' => $this->config['region'],
            'credentials' => array(
                'secretId' => $this->config['access_key'],
                'secretKey' => $this->config['secret_key'],
            )
        ));
        ### 上传文件流
        try {
            $content = file_get_contents($url);
            $result = $cosClient->putObject(array(
                'Bucket' => $this->config['bucket'],
                'Key' => $key,
                'Body' => $content));
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            return false;
        }
        return true;
    }

    /**
     * @notes 删除文件
     * @param $fileName
     * @return bool|mixed
     */
    public function delete($fileName)
    {
        $cosClient = new Client(array(
            'region' => $this->config['region'],
            'credentials' => array(
                'secretId' => $this->config['access_key'],
                'secretKey' => $this->config['secret_key'],
            )
        ));
        // 删除COS对象
        $result = $cosClient->deleteObject(array(
            'Bucket' => $this->config['bucket'],
            'Key' => $fileName));
    }

    /**
     * 返回文件路径
     * @return mixed
     */
    public function getFileName()
    {
        return $this->fileName;
    }
}
